package com.link.base.base.forgetpass.controller;

import com.link.base.base.user.model.User;
import com.link.base.base.common.model.ForgetPassWord;
import com.link.base.base.forum.model.Forum;
import com.link.base.base.user.model.UserChange;
import com.link.base.base.user.service.UserService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.AppConstants;
import com.link.core.util.StringUtils;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 忘记密码
 *
 * @author 阳晓琳
 * @date 2019/12/12 14:30 update
 */
@Controller
@RequestMapping("/security/forword")
public class ForgetPassController {
    char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G',
        'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
        'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    @Resource
    private UserService userService;
    //邮箱验证码
    private int emailCodeCount = 6;//邮箱验证码个数

    private static final Pattern PATTERN = Pattern.compile(
            "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");

    /**
     * 验证码变量定义
     */
    private int width = 90;//定义图片的width
    private int height = 20;//定义图片的height
    private int codeCount = 4;//定义图片上显示验证码的个数
    private int xx = 15;
    private int fontHeight = 18;
    private int codeY = 16;

    @RequestMapping(value = "/forgetPass/step1", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView step1(Forum record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        try {
            mav.setViewName("security/forgetPassword_step1");
            session.setAttribute("resetPassWordStep", "step1");
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return mav;
    }

    @RequestMapping(value = "/forgetPass/step2", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView step2(Forum record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        try {
            String step = (String) session.getAttribute("resetPassWordStep");
            String stepTwo = "step2";
            if (stepTwo.equals(step)) {
                mav.setViewName("security/forgetPassword_step2");
                session.setAttribute("resetPassWordStep", "step2");
            } else {
                session.removeAttribute("resetPassWordStep");
                return new ModelAndView("redirect:/login.jsp");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return mav;
    }

    @RequestMapping(value = "/forgetPass/step3", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView step3(Forum record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        try {
            String step = (String) session.getAttribute("resetPassWordStep");
            String stepThree = "step3";
            if (stepThree.equals(step)) {
                mav.setViewName("security/forgetPassword_step3");
                session.setAttribute("resetPassWordStep", "step3");
            } else {
                session.removeAttribute("resetPassWordStep");
                return new ModelAndView("redirect:/login.jsp");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return mav;
    }

    @RequestMapping(value = "/forgetPass/step4", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView step4(Forum record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        try {
            String step = (String) session.getAttribute("resetPassWordStep");
            String setpFour = "step4";
            if (setpFour.equals(step)) {
                mav.setViewName("security/forgetPassword_step4");
                session.setAttribute("resetPassWordStep", "step4");
            } else {
                session.removeAttribute("resetPassWordStep");
                return new ModelAndView("redirect:/login.jsp");
            }
        } catch (Exception e) {
            LCLogger.withException(e);
        }
        return mav;
    }

    /**
     * 生成验证码
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping("/code")
    public void getCode(HttpServletRequest req, HttpServletResponse resp) {
        try {
            // 定义图像buffer
            BufferedImage buffImg = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            //Graphics2D gd = buffImg.createGraphics();
            //Graphics2D gd = (Graphics2D) buffImg.getGraphics();
            Graphics gd = buffImg.getGraphics();
            // 创建一个随机数生成器类
            Random random = new Random();
            // 将图像填充为白色
            gd.setColor(Color.WHITE);
            gd.fillRect(0, 0, width, height);

            // 创建字体，字体的大小应该根据图片的高度来定。
            Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
            // 设置字体。
            gd.setFont(font);

            // 画边框。
            gd.setColor(Color.BLACK);
            gd.drawRect(0, 0, width - 1, height - 1);

            // 随机产生40条干扰线，使图象中的认证码不易被其它程序探测到。
            gd.setColor(Color.BLACK);
            //40条干扰线
            int lineNum = 40;
            for (int i = 0; i < lineNum; i++) {
                int x = random.nextInt(width);
                int y = random.nextInt(height);
                int xl = random.nextInt(12);
                int yl = random.nextInt(12);
                gd.drawLine(x, y, x + xl, y + yl);
            }

            // randomCode用于保存随机产生的验证码，以便用户登录后进行验证/。
            StringBuffer randomCode = new StringBuffer();
            int red = 0;
            int green = 0;
            int blue = 0;

            // 随机产生codeCount数字的验证码。
            for (int i = 0; i < codeCount; i++) {
                // 得到随机产生的验证码数字。
                // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同。
                red = random.nextInt(255);
                green = random.nextInt(255);
                blue = random.nextInt(255);

                // 用随机产生的颜色将验证码绘制到图像中。
                gd.setColor(new Color(red, green, blue));
                String code = String.valueOf(codeSequence[random.nextInt(36)]);
                gd.drawString(code, (i + 1) * xx, codeY);

                // 将产生的四个随机数组合在一起。
                randomCode.append(code);
            }
            // 将四位数字的验证码保存到Session中。
            HttpSession session = req.getSession();
            System.out.print(randomCode);
            session.setAttribute("code", randomCode.toString());

            // 禁止图像缓存。
            resp.setHeader("Pragma", "no-cache");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setDateHeader("Expires", 0);

            resp.setContentType("image/jpeg");

            // 将图像输出到Servlet输出流中。
            ServletOutputStream sos = resp.getOutputStream();
            ImageIO.write(buffImg, "jpeg", sos);
            sos.close();
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * 校验输入用户及验证码是否正确
     */
    @RequestMapping(value = "/validateAccount", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> validateAccount(Forum record, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>();
        String forgetEmail = null;
        if (record == null) {
            throw new ServiceException("FORGET-001");
        }
        String accntName = record.getNoteTitle();
        if (StringUtils.isBlank(accntName)) {
            throw new ServiceException("PUBLIC-046");
        }
        String codeContent = record.getSimpleNote().toUpperCase();
        if (StringUtils.isBlank(codeContent)) {
            throw new ServiceException("PUBLIC-047");
        }
        try {
            //用户账号校验
            User user = userService.getUserByUsername(accntName);
            if (user == null) {
                throw new ServiceException("FORGET-002");
            }
            forgetEmail = user.getEmail();
            //验证码校验
            String validateCode = (String) session.getAttribute("code");
            if (!codeContent.equals(validateCode)) {
                throw new ServiceException("PUBLIC-048");
            }
            session.setAttribute("forgetUserName", accntName);
            session.setAttribute("forgetEmail", forgetEmail);
            session.setAttribute("resetPassWordStep", "step2");
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    ;

    /**
     * 给用户邮箱发送验证码
     *
     * @param qps
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/getEmailCode", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmailCode(QueryParams qps, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        //生成6位邮箱验证码
        StringBuffer emialCode = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < emailCodeCount; i++) {
            // 得到随机产生的验证码数字。
            String code = String.valueOf(codeSequence[random.nextInt(36)]);
            // 将产生的六个随机数组合在一起。
            emialCode.append(code);
        }

        String emailCode = emialCode.toString();
        try {
            String htmlEmailTemplate = "您的验证码:" + emailCode + "</br>此验证码30分钟内有效，请及时输入。</br> linking you and me";
            HtmlEmail email = new HtmlEmail();
            email.setHostName("smtp.sina.com");
            email.setCharset("UTF-8");
            email.setSmtpPort(465);
            email.setAuthenticator(new DefaultAuthenticator("linkcrm", "handhand"));
            email.setSSLOnConnect(true);
            email.setFrom("linkcrm@sina.com", "Link CRM");
            email.setSubject("重置密码验证码");
            email.setHtmlMsg(htmlEmailTemplate);
            //session中获取邮箱,并校验邮箱格式是否正确
            String forgetEmail = (String) session.getAttribute("forgetEmail");
//            Pattern pattern = Pattern.compile(
//                    "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)
// |(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
            Matcher matcher = PATTERN.matcher(forgetEmail);
            boolean isChecked = matcher.matches();
            if (!isChecked) {
                throw new ServiceException("PUBLIC-049");
            }
            email.addTo(forgetEmail, "hand");
            email.send();
            session.setAttribute("emailCode", emailCode);
            Date now = new Date();
            session.setAttribute("emailCodeDt", now);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * 提交邮箱验证
     *
     * @param record
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/validateEmailCode", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> validateEmailCode(ForgetPassWord record, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            String emailCode = (String) session.getAttribute("emailCode");
            String inputEmailCode = record.getEmailCode();
            Date emailCodeDt = (Date) session.getAttribute("emailCodeDt");    //邮箱验证码发送时间
            Date now = new Date();
            long diff = now.getTime() - emailCodeDt.getTime();
            long minutes = diff / (1000 * 60);
            if (!inputEmailCode.equals(emailCode)) {
                throw new ServiceException("PUBLIC-048");
            } else {
                //邮箱验证码30分钟内有效
                int validMinutes = 30;
                if (minutes > validMinutes) {
                    throw new ServiceException("PUBLIC-050");
                }
            }
            session.setAttribute("resetPassWordStep", "step3");
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("result", e.getLocalizedMessage());
        }
        return result;
    }

    /**
     * 密码重置
     *
     * @param userChange
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> resetPassword(UserChange userChange, HttpSession session, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        String accntName = (String) session.getAttribute("forgetUserName");
        User user = userService.getUserByUsername(accntName);
        if (user == null) {
            throw new ServiceException("ENTER-002");
        }
        try {
            if (userChange != null) {
                LCLogger.info().withMessageKey("resetPassword").withMessage(AppConstants.LOG_DIVISION_LINE + "reset password start！").flush();
                userService.resetPassword(user, userChange.getNewPassword(), userChange.getConfirmPassword());
                LCLogger.info().withMessageKey("resetPassword").withMessage(AppConstants.LOG_DIVISION_LINE + "reset password end！").flush();
            } else {
                LCLogger.info().withMessageKey("resetPassword").withMessage(AppConstants.LOG_DIVISION_LINE + "the info of password is null！").flush();
                throw new ServiceException("PUBLIC-051");
            }
            session.setAttribute("resetPassWordStep", "step4");
            //销毁相关session变量
            session.removeAttribute("code");
            session.removeAttribute("forgetUserName");
            session.removeAttribute("forgetEmail");
            session.removeAttribute("emailCode");
            session.removeAttribute("emailCodeDt");
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.error().withMessageKey("resetPassword").withMessage(AppConstants.LOG_DIVISION_LINE + e.getMessage()).flush();
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}

